using memo.entity.PO;
using memo.entity.VO;
using SqlSugar;
using System.Collections.Generic;

namespace memo.Services
{
    public class MemoService
    {
        private readonly SqlSugarScope _db;
        public MemoService(SqlSugarScope db)
        {
            _db = db;
        }

        public int AddMemo(Memo memo)
        {
            memo.CreateTime = DateTime.Now;
            return _db.Insertable(memo).ExecuteReturnIdentity();
        }

        public int DeleteMemo(int id)
        {
            return _db.Deleteable<Memo>(id).ExecuteCommand();
        }

        public int UpdateMemo(Memo memo)
        {
            memo.UpdateTime = DateTime.Now;
            return _db.Updateable(memo)
                        .IgnoreColumns(ignoreAllNullColumns:true)
                        .ExecuteCommand();
        }

        public List<Memo> GetAllMemos()
        {
            return _db.Queryable<Memo>().ToList();
        }

        public PageVo<Memo> GetMemosByPage(int current, int size)
        {
            var totalCount = 0;
            var totalPage = 0;
            var list = _db.Queryable<Memo>()
                        .OrderBy(m => m.Id, OrderByType.Desc)
                        .ToPageList(current, size, ref totalCount, ref totalPage);
            return new PageVo<Memo>(current: current, size: size, total: totalCount, list: list);
        }

        public Memo? GetMemoById(int id)
        {
            return _db.Queryable<Memo>().Where(m => m.Id == id).First();
        }

        public PageVo<Memo> GetMemosByUserId(int userId, int current, int size)
        {
            var totalCount = 0;
            var totalPage = 0;
            var memoList = _db.Queryable<Memo>()
                        .Where(m => m.UserId == userId)
                        .OrderBy(m => m.Id, OrderByType.Desc)
                        .ToPageList(current, size, ref totalCount, ref totalPage);
            return new PageVo<Memo>(current: current, size: size, total: totalCount, list: memoList);
        }
    }
} 